import pickle
import tkinter as tk
from playsound import playsound
import time

import json
from playwright.sync_api import Playwright, sync_playwright, expect

def getcookie(playwright: Playwright) -> None:
    zhanghao=data["zhanghao"]
    xueqi=data["xueqi"]
    xueqi=xueqi[0]
    zhanghao = str(zhanghao)
    mima=data["mima"]
    mima = mima[0]
    mima = str(mima)
    kechenghao = data["kechenghao"]
    jiaoshihao=data["jiaoshihao"]
    browser = playwright.chromium.launch(headless=False)
    context = browser.new_context()

    # Open new page
    page = context.new_page()
    page.goto("https://oauth.shu.edu.cn/login/eyJ0aW1lc3RhbXAiOjE2NzYyMjIzODU0NDk5OTQzMzgsInJlc3BvbnNlVHlwZSI6ImNvZGUiLCJjbGllbnRJZCI6InlSUUxKZlVzeDMyNmZTZUtOVUN0b29LdyIsInNjb3BlIjoiIiwicmVkaXJlY3RVcmkiOiJodHRwOi8veGsuYXV0b2lzcC5zaHUuZWR1LmNuL3Bhc3Nwb3J0L3JldHVybiIsInN0YXRlIjoiIn0=")
    page.wait_for_load_state('load')
    time.sleep(2)
    page.get_by_placeholder("请输入学工号").click()
    page.get_by_placeholder("请输入学工号").fill(zhanghao)
    page.get_by_placeholder("请输入密码").click()
    page.get_by_placeholder("请输入密码").fill(mima)
    page.get_by_role("button", name="登录").click()
    time.sleep(3)
    page.goto("http://xk.autoisp.shu.edu.cn/Home/TermIndex")
    page.get_by_role("cell", name=xueqi).click()
    page.get_by_role("button", name=" 确定").click()
    page.locator("#CourseSelectionStudentFuzzyQuery").get_by_role("link", name=" 选课").click()


    storage = context.storage_state()
    with open("账号数据/cookie.json", "w") as f:
        f.write(json.dumps(storage))

    # Close page
    page.close()

    # ---------------------
    context.close()
    browser.close()
def run(playwright: Playwright) -> None:
    kehenghao = data["kechenghao"]
    jiaoshihao=data["jiaoshihao"]
    xueqi=data["xueqi"]
    xueqi=xueqi[0]
    kehenghao = kehenghao[0]
    kehenghao=str(kehenghao)
    jiaoshihao=str(jiaoshihao)
    timegap = data["timegap"]
    timegap = int(timegap)
    open_brose=data["open_brose"]
    open_brose=int(open_brose)
    if open_brose==1:
        headless = False
    else:
        headless = True
    browser = playwright.chromium.launch(headless=headless)  # headless=False
    # 加载状态
    with open(f"账号数据/cookie.json") as f:
        storage_state = json.loads(f.read())
    context = browser.new_context(storage_state=storage_state)
    # Open new page
    page = context.new_page()
    page.goto("http://xk.autoisp.shu.edu.cn/Home/TermIndex")
    time.sleep(2)
    page.get_by_role("cell", name=xueqi).click()
    page.get_by_role("button", name=" 确定").click()
    print("点击确定")
    time.sleep(2)
    page.get_by_role("link", name=" 选课", exact=True).click()
    print("点击选课")
    a=1
    while  a ==1:
        try:
            page.locator("input[name=\"CID\"]").click()
            page.locator("input[name=\"CID\"]").fill(kehenghao)
            page.locator("input[name=\"TeachNo\"]").click()
            page.locator("input[name=\"TeachNo\"]").fill(jiaoshihao)
            page.locator("input[name=\"TimeText\"]").click()
            page.get_by_role("button", name=" 查询").click()
            print("点击查询")
            time.sleep(timegap)
            try:
                button1 = page.locator("input[name=\"checkclass\"]")
                button1.check(timeout=1000)
                t = page.locator("text='人数已满'")
                print("人数已满")
                # print(t.count())
                assert (t.count() != 0)
                continue
            except:
                button = page.get_by_role("button", name="确定")
                button.click()
                print("点击确定")
                # page.get_by_role("button", name=" 确定").click()
                time.sleep(1)

                page.get_by_role("button", name="关闭").click()
                print("点击关闭")
                playsound('刘德华-恭喜发财.wma')
                a = 0

        except:
            page.goto("http://xk.autoisp.shu.edu.cn/Home/TermIndex")
            time.sleep(2)
            page.get_by_role("cell", name=xueqi).click()
            page.get_by_role("button", name=" 确定").click()
            print("点击确定")
            time.sleep(2)
            page.locator("#CourseSelectionStudentFuzzyQuery").get_by_role("link", name=" 选课").click()
            print("点击选课")

        # page.goto("http://xk.autoisp.shu.edu.cn/CourseSelectionStudent/FuzzyQuery")


    # ---------------------
    context.close()
    browser.close()
def getcookieplay():
    with sync_playwright() as playwright:
        getcookie(playwright)

def main():
    with sync_playwright() as playwright:
        run(playwright)



def load_pickle():
    filename = '账号数据/设置.json'
    with open( filename, 'r', encoding='utf-8' ) as f:
        global data
        data = json.load( f )
        display_data()


def display_data():
    global data
    data_text.delete('1.0', tk.END)
    for key, value in data.items():
        data_text.insert(tk.END, '{}: {}\n'.format(key, value))


def update_data():
    global data
    lines = data_text.get('1.0', tk.END).split('\n')
    data = {}
    for line in lines:
        line = line.strip()
        if not line:
            continue
        key, value = line.split(':', 1)
        data[key.strip()] = eval(value.strip())
    with open('账号数据/设置.json', 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=4)  # 使用ensure_ascii=False和indent=4使JSON更易读
root = tk.Tk()
root.title("夕年脚本3.8")

getcookieplay_button = tk.Button(root, text="获取cookie", command=getcookieplay)
getcookieplay_button.pack()

load_button = tk.Button(root, text="加载配置", command=load_pickle)
load_button.pack()

data_text = tk.Text(root, height=40, width=60)
data_text.pack()

update_button = tk.Button(root, text="更新配置", command=update_data)
update_button.pack()


run_button = tk.Button(root, text="开始抢课", command=main)
run_button.pack()

root.mainloop()

